package com.kchouse.mine;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.CashRecordItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.bean.MineCouponItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.myadapter.CashRecordAdapter;
import com.kchouse.myadapter.UnionAdapter;
import com.kchouse.view.ProgressView;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;

public class UserecordActivity extends BaseActivity implements View.OnClickListener {

    private UserecordActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item;
    private Intent intent;
    private boolean isCash;//是否是现金券
    private TextView tv_item;
    private HaoRecyclerView hao_recycleview;
    private int page = 1;
    private int totalCount;//总个数
    private ArrayList<CashRecordItem> listcashrecordlist = new ArrayList<>();
    private ArrayList<MineCouponItem> listcouponsrecordlist = new ArrayList<>();
    private CashRecordAdapter cashrecordAdapter;
    private int cashNum;//现金券数量
    private CouponsRecordAdapter couponsadapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userecord);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_item = (TextView) findViewById(R.id.tv_item);

        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        lv_item = (ListView) findViewById(R.id.lv_item);
        couponsadapter = new CouponsRecordAdapter();
        lv_item.setAdapter(couponsadapter);

        hao_recycleview = (HaoRecyclerView) findViewById(R.id.hao_recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContent);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hao_recycleview.setLayoutManager(layoutManager);
        //添加Android自带的分割线
//        hao_recycleview.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

        //设置自定义加载中和到底了效果
        ProgressView progressView = new ProgressView(mContent);
        progressView.setIndicatorId(ProgressView.BallPulse);
        progressView.setIndicatorColor(0xff69b3e0);
        hao_recycleview.setFootLoadingView(progressView);
        cashrecordAdapter = new CashRecordAdapter(mContent, listcashrecordlist);
        hao_recycleview.setAdapter(cashrecordAdapter);

        hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        page = page + 1;
                        GetCashRecordList(page);
                        hao_recycleview.loadMoreComplete();

                    }
                }, 2000);
            }
        });

        if (isCash) {
            tv_title.setText("现金券记录");
            tv_item.setText("当前现金券余额" + (cashNum * 10) + "元");
            lv_item.setVisibility(View.GONE);
            hao_recycleview.setVisibility(View.VISIBLE);
        } else {
            tv_title.setText("优惠券记录");
//            tv_item.setText("当前优惠券X");
            lv_item.setVisibility(View.VISIBLE);
            hao_recycleview.setVisibility(View.GONE);
        }
    }

    class CouponsRecordAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listcouponsrecordlist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MineCouponItem item = listcouponsrecordlist.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_integral_item, null);
            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_merchantName.setText(item.getMerchantShortName());
            TextView tv_suitName = (TextView) view.findViewById(R.id.tv_suitName);
            tv_suitName.setText(item.getCouponTemplateName());
            TextView tv_useStatus = (TextView) view.findViewById(R.id.tv_useStatus);
            TextView tv_createTime = (TextView) view.findViewById(R.id.tv_createTime);
            if (TextUtils.isEmpty(item.getUseTime())) {
                tv_createTime.setText(item.getEndTime());
            } else {
                tv_createTime.setText(item.getUseTime());
            }
            if (item.getUseStatus().equals("USED")) {
                tv_useStatus.setText("已使用");
            } else {
                tv_useStatus.setText("已过期");
            }
            return view;
        }
    }

    private void intiData() {

        intent = getIntent();
        isCash = intent.getBooleanExtra("isCash", true);

        if (isCash) {
//            tv_title.setText("现金券记录");
//            tv_item.setText("当前现金券余额");

            GetCashRecordList(page);
            cashNum = intent.getIntExtra("cashNum", 0);
        } else {
//            tv_title.setText("优惠券记录");
//            tv_item.setText("当前优惠券余额");
            GetMineCouponsRecord();

        }
    }

    /**
     * 获取我的优惠券使用记录
     */
    private void GetMineCouponsRecord() {
        String url = API.GetMineCouponsRecord + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("token", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    listcouponsrecordlist.addAll(JSONObject.parseArray(datastr, MineCouponItem.class));
                    tv_item.setText("已使用优惠券" + listcouponsrecordlist.size() + "张");
                    couponsadapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 获取现金券记录列表
     *
     * @param page
     */
    private void GetCashRecordList(int page) {
        String url = API.GetCashRecordList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addHeader("token", MainActivity.token);//添加header信息

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listcashrecordlist.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                    } else {
                        listcashrecordlist.addAll(JSONObject.parseArray(data.getString("cashRecordList"), CashRecordItem.class));
                        cashrecordAdapter.notifyDataSetChanged();
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
